package com.jifeng.sterilizer.service.impl;

import com.jifeng.sterilizer.constant.WXUrlConstant;
import com.jifeng.sterilizer.entity.*;
import com.jifeng.sterilizer.service.ControllerService;
import com.jifeng.sterilizer.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jifeng.sterilizer.dao.UserControllerDao;
import com.jifeng.sterilizer.entity.UserControllerEntity;
import com.jifeng.sterilizer.service.UserControllerService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Service("userControllerService")
@Slf4j
public class UserControllerServiceImpl extends ServiceImpl<UserControllerDao, UserControllerEntity> implements UserControllerService {


    @Autowired
    ControllerService controllerService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserControllerEntity> page = this.page(
                new Query<UserControllerEntity>().getPage(params),
                new QueryWrapper<UserControllerEntity>()
        );

        return new PageUtils(page);
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Override
    public R getListUserControllers(Map<String, Object> params) {
        try {
            HttpServletRequest request = getRequest();
            String requestURI = request.getRequestURI();
            Integer uid = Integer.valueOf(String.valueOf(params.get("userId")));
            if (requestURI.equals(WXUrlConstant.WX_LIST_USER_CONTROLLER)) {
                Map userInfo = HttpUtils.getTokenInfo(request);
                Object tokenId = userInfo.get("id");
                if (!tokenId.equals(uid)) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的中控器信息", "只能查询本用户的数据");
                    return R.error(400, "只能查询本用户的数据");
                }
            }
            List<Map<String, Object>> mapList = new ArrayList<>();
            List<UserControllerEntity> userControllerEntityList = this.list(new QueryWrapper<UserControllerEntity>().eq("user_id", uid));
            if (userControllerEntityList.isEmpty()) {
                log.warn("方法：{}，错误信息：{}", "获取用户绑定的中控器信息", "无效的用户id");
                return R.ok().put("data", mapList);
            }
            userControllerEntityList.forEach(userControllerEntity -> {
                Map<String, Object> map = new HashMap<>();
                Long controllerNumber = userControllerEntity.getControllerNumber();
                if (controllerNumber == null) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的中控器信息", "用户绑定的中控器编号为空");
                    return;
                }
                ControllerEntity controllerEntity = controllerService.getOne(new QueryWrapper<ControllerEntity>()
                        .eq("number", controllerNumber));
                if (controllerEntity == null) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的中控器信息", "用户绑定的中控器为空");
                    return;
                }
                String name = controllerEntity.getName();
                Long id = controllerEntity.getId();
                map.put("id", id);
                map.put("number", controllerNumber);
                map.put("name", name);
                mapList.add(map);
            });
            return R.ok().put("data", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取用户绑定的中控器信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

    @Override
    public R addUserController(UserControllerEntity userControllerEntity) {
        boolean save = this.save(userControllerEntity);
        Map<String, Object> map = new HashMap<>();
        if (save) {
            ControllerEntity controllerEntity = controllerService.getOne(new QueryWrapper<ControllerEntity>().eq("number", userControllerEntity.getControllerNumber()));
            map.put("number", userControllerEntity.getControllerNumber());
            map.put("name", controllerEntity.getName());
            return R.ok().put("data", map);
        }
        return R.error();
    }

    @Override
    public R removeUserController(UserControllerEntity userController) {
        try {
            boolean isNumber = RegexUtils.isNumber(String.valueOf(userController.getControllerNumber()), 2);
            if (!isNumber) {
                log.warn("方法：{}，错误信息：{}", "解除用户和中控器的绑定", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            boolean remove = this.remove(new QueryWrapper<UserControllerEntity>().eq("user_id", userController.getUserId()).eq("controller_number", userController.getControllerNumber()));
            if (remove) {
                return R.ok();
            }
            log.warn("方法：{}，错误信息：{}", "解除用户和中控器的绑定", "检查提交参数值是否有效");
            return R.error(400, "检查提交参数值是否有效");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "解除用户和中控器的绑定", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

}